package tools.project.controller.action
{
	import flash.display.BitmapData;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	
	import ghostcat.fileformat.png.PNGEncoder;
	
	import kiwi.action.Action;
	import kiwi.action.queue.Queue;
	import kiwi.debug.Log;
	import kiwi.event.ActionEvent;
	import kiwi.util.ArrayUtils;
	import kiwi.util.sprintf;
	import kiwi.util.bitmap.BitmapUtil;
	
	import tools.model.ActionFrameInfo;
	import tools.model.ActionInfo;
	import tools.model.EditorConfig;
	import tools.model.FrameInfo;
	import tools.model.TextureTypeEnum;
	import tools.model.TileInfo;
	import tools.utils.MaxRectsBinPack;
	import tools.utils.SaveSmallPackageUtil;

	public class SaveSmallXmlAction extends Action
	{
		
		private var dir : String;
		private var config:EditorConfig;
		private var queue:Queue;
		
		public function SaveSmallXmlAction(dirs:String,configs:EditorConfig)
		{
			this.dir = dirs;
			this.config = configs;
		}
		
		
		override public function execute() : void {
			super.execute();
			queue = new Queue(null);
			
			var eachKeyDic:Dictionary = new Dictionary();
			var keyDic : Dictionary = new Dictionary();
			
			for each(var actionInfo:ActionInfo in config.actionList){
				var acIndex:int = TextureTypeEnum.ACTION_STR.indexOf(actionInfo.name);
				if(acIndex >= 0){
					if(eachKeyDic[TextureTypeEnum.CONVENT_STR[acIndex]] && eachKeyDic[TextureTypeEnum.CONVENT_STR[acIndex]] is Array){
						eachKeyDic[TextureTypeEnum.CONVENT_STR[acIndex]] = (eachKeyDic[TextureTypeEnum.CONVENT_STR[acIndex]]  as Array).concat(actionInfo);
					}else{
						eachKeyDic[TextureTypeEnum.CONVENT_STR[acIndex]] = [actionInfo];
						keyDic[TextureTypeEnum.CONVENT_STR[acIndex]] = TextureTypeEnum.CONVENT_STR[acIndex];
					}
				}
			}
			
			// 解析文件夹以及旗下的。png 并绘图
			
			for each(var arrKey:Object in keyDic){
				if(arrKey && eachKeyDic[arrKey] is Array){
					// result 
					var result:XML = <config></config>;
					// tiles部分
					var tiles : XML = <tiles></tiles>;
					// frame部分
					var frames : XML = <frames></frames>;
					// action部分
					var actions : XML = <actions></actions>;
					
					var pack : MaxRectsBinPack = new MaxRectsBinPack(4096, 4096);
					var tempFile : File;
					var tempOP:FileStream;
					var canvas : BitmapData = new BitmapData(4096, 4096, true, 0x0);
					canvas.lock();
					
					for each (var action:ActionInfo in eachKeyDic[arrKey]){
						actions.appendChild(createXMLByObject("action", {scale:action.scale, name:action.name, frame_duration:ArrayUtils.collect(action.frameList, "duration").join(","), frame:ArrayUtils.collect(ArrayUtils.collect(action.frameList, "frame"), "id").join(",")}));
						for each(var frame:ActionFrameInfo in action.frameList){
							frames.appendChild(createXMLByObject("frame", {id:frame.frame.id, tile:ArrayUtils.collect(frame.frame.tileList, "id").join(",")}));
							for each(var tile:TileInfo in frame.frame.tileList){
								var tmp:Rectangle = pack.insert(tile.source.width, tile.source.height, MaxRectsBinPack.METHOD_RECT_BEST_AREA_FIT);
								tiles.appendChild(createXMLByObject("tile", {id:tile.id, source:{x:tmp.x, y:tmp.y, width:tmp.width, height:tmp.height}, registration:{x:tile.registration.x, y:tile.registration.y}}));
								canvas.copyPixels(tile.$cached,tile.$cached.rect,tmp.topLeft,null,null,true);
							}
						}
					}
					
					result.appendChild(tiles);
					result.appendChild(frames);
					result.appendChild(actions);
					
					queue.submit(new SaveXMLAction(dir+"/"+arrKey+".xml",result));
					
					canvas.unlock();
					canvas = BitmapUtil.trim(canvas, null);
					
					
					tempFile = File.applicationDirectory.resolvePath(dir + "/"+ arrKey +".png");
					tempOP = new FileStream();
					tempOP.open(tempFile, FileMode.WRITE);
					tempOP.writeBytes(PNGEncoder.encode(canvas));
					tempOP.close();
					
					
					// 生成 分包
					new SaveSmallPackageUtil(dir,arrKey+"",80);
					
				}
			}
			queue.addEventListener(ActionEvent.ACTION_COMPLETE, onComplete);
			queue.execute();
		}
		
		private function createXMLByObject(title : String, obj : *) : XML {
			if (obj is int || obj is Number || obj is String || obj is Boolean || obj is uint) {
				return new XML(sprintf("<%s>%s</%s>", title, obj, title));
			}
			var xml : XML = new XML(sprintf("<%s></%s>", title, title));
			for (var key:String in obj) {
				var subXML : XML;
				if (obj[key] is Array) {
					subXML = new XML(sprintf("<%s></%s>", key, key));
					for each (var subObj:* in obj[key]) {
						subXML.appendChild(createXMLByObject("item", subObj));
					}
				} else {
					subXML = createXMLByObject(key, obj[key]);
				}
				xml.appendChild(subXML);
			}
			return xml;
		}
		
		private function onComplete(event : ActionEvent) : void {
			Log.alert("发布小包包完毕");
			result();
		}
	}
}